#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据处理模块
"""

import pandas as pd
import numpy as np
from typing import Dict, Any, Optional, List
import logging

from ..config.settings import AppConfig
from ..utils.logger import get_logger
from .data_utils_system import (
    calculate_ahs_couponed_price, calculate_zz_couponed_price,
    calculate_strategy_value, calculate_strategy_quote_price,
    level_order, level_hierarchy, calculate_inversion_statistics,
    calculate_big_gap_value, calculate_big_gap_value_human,
    define_competiitive_starts_ends, modify_tens_price
)

logger = get_logger(__name__)

class DataProcessor:
    """数据处理器"""
    
    def __init__(self, config: AppConfig):
        self.config = config
    
    def calculate_ahs_couponed_price(self, price: float) -> float:
        """
        计算AHS券后价格
        
        Args:
            price: 券前价格
        
        Returns:
            券后价格
        """
        # 使用从data_utils_system导入的函数
        return calculate_ahs_couponed_price(price)
    
    def calculate_zz_couponed_price(self, price: float) -> float:
        """
        计算转转券后价格
        
        Args:
            price: 券前价格
        
        Returns:
            券后价格
        """
        # 使用从data_utils_system导入的函数
        return calculate_zz_couponed_price(price)
    
    def calculate_strategy_value(self, price: float) -> float:
        """
        计算策略中间值
        
        Args:
            price: 输入价格
        
        Returns:
            策略中间值
        """
        # 使用从data_utils_system导入的函数
        return calculate_strategy_value(price)
    
    def calculate_inversion_statistics(self, df: pd.DataFrame, price_column: str) -> pd.DataFrame:
        """
        计算倒挂统计
        
        Args:
            df: 数据框
            price_column: 价格列名
        
        Returns:
            倒挂统计结果
        """
        # 使用从data_utils_system导入的函数
        return calculate_inversion_statistics(df, price_column)
    
    def validate_data(self, data: pd.DataFrame) -> Dict[str, Any]:
        """
        验证数据质量
        
        Args:
            data: 要验证的数据
        
        Returns:
            验证结果
        """
        try:
            validation_result = {
                'is_valid': True,
                'issues': [],
                'statistics': {}
            }
            
            # 检查必要列是否存在
            required_columns = ['product_name', 'product_sku_name', 'product_level_name', 'finalprice']
            missing_columns = [col for col in required_columns if col not in data.columns]
            
            if missing_columns:
                validation_result['is_valid'] = False
                validation_result['issues'].append(f"缺少必要列: {missing_columns}")
            
            # 检查数据完整性
            null_counts = data.isnull().sum()
            if null_counts.any():
                validation_result['issues'].append(f"存在空值: {null_counts[null_counts > 0].to_dict()}")
            
            # 检查价格数据
            if 'finalprice' in data.columns:
                price_stats = data['finalprice'].describe()
                validation_result['statistics']['price_stats'] = price_stats.to_dict()
                
                # 检查异常价格
                if (data['finalprice'] <= 0).any():
                    validation_result['issues'].append("存在非正价格")
            
            # 统计信息
            validation_result['statistics']['total_records'] = len(data)
            validation_result['statistics']['unique_products'] = data['product_name'].nunique() if 'product_name' in data.columns else 0
            validation_result['statistics']['unique_skus'] = data['product_sku_name'].nunique() if 'product_sku_name' in data.columns else 0
            
            logger.info(f"数据验证完成，有效性: {validation_result['is_valid']}")
            return validation_result
            
        except Exception as e:
            logger.error(f"数据验证失败: {str(e)}")
            raise
    
    def clean_data(self, data: pd.DataFrame) -> pd.DataFrame:
        """
        清理数据
        
        Args:
            data: 原始数据
        
        Returns:
            清理后的数据
        """
        try:
            cleaned_data = data.copy()
            
            # 移除空值行
            cleaned_data = cleaned_data.dropna(subset=['product_name', 'finalprice'])
            
            # 移除无效价格
            cleaned_data = cleaned_data[cleaned_data['finalprice'] > 0]
            
            # 移除重复行
            cleaned_data = cleaned_data.drop_duplicates()
            
            # 数据类型转换
            if 'finalprice' in cleaned_data.columns:
                cleaned_data['finalprice'] = pd.to_numeric(cleaned_data['finalprice'], errors='coerce')
            
            # 移除转换失败的行
            cleaned_data = cleaned_data.dropna(subset=['finalprice'])
            
            logger.info(f"数据清理完成，从 {len(data)} 行减少到 {len(cleaned_data)} 行")
            return cleaned_data
            
        except Exception as e:
            logger.error(f"数据清理失败: {str(e)}")
            raise